const app = getApp()
var api = require('../../utils/api.js')
var util = require('../../utils/util.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    itemData: {},
    region: ['请选择所在地区', '', ''],

    tishiType: 1, //1:送的礼品，2:抽奖礼品
    giftTitle: '获得一次抽奖机会~', //礼物标题
    gifttext: '', //礼物文字
    giftButton: '', //礼物按钮
    isShowButton: false, //是否显示抽中提示按钮
  
    isShowGift: false, //是否显示礼品
    // gift:{type:2,get_type:1},
    isShowAward: false, //是否显示抽奖
    circleList: [],//圆点数组
    awardList: [],//奖品数组
    colorCircleFirst: '#FFDF2F',//圆点颜色1
    colorCircleSecond: '#FE4D32',//圆点颜色2
    colorAwardDefault: '#F5F0FC',//奖品默认颜色
    colorAwardSelect: '#F53605',//奖品选中颜色
    indexSelect: 0,//被选中的奖品index
    isRunning: false,//是否正在抽奖
    giftList: [],//后台奖品
    winning_numbers: 0, //中奖下标0-7
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var oid = options.oid;
    var types = options.types;
    // var oid = 7;
    wx.getSystemInfo({
      success: function (res) {
        console.log(res)
        that.setData({
          windowHeight: res.windowHeight
        })
      }
    })
    that.setData({
      oid: oid,
      types: types
    })
    this.circleList();
    this.orderInfo(oid);
  },


  //订单信息
  orderInfo: function (oid) {
    var that = this;
    var orderInfo = wx.getStorageSync('orderData');
    that.setData({
      itemData: orderInfo
    });
    that.receiveGift(orderInfo)
  },

  //完成
  link: function () {
    wx.switchTab({
      url: '../index/index'
    })
  },
  //支付成功是否送礼品
  receiveGift: function (orderInfo) {
    var that = this;
    api.POST({
      params: { oid: orderInfo.oid },
      url: app.globalData.receive_gift_url,
      success: function (res) {
        if (res.data.code == '') {
          that.setData({
            gift: { code_img: res.data.data.img_url }
          })
        } else {
          that.getlist();
        }
      },
      fail: function (fail) {
        util.showError("网络错误");
        that.getlist();
      }
    })
  },

  //检查是否抽奖
  checkChouJiang:function(){
      this.getlist();
  },

  //抽奖奖品列表
  getlist: function () {
    var that = this;
    that.setData({
      tishiType:2,
      gift:{}
    })
    api.POST({
      params: { order_id: that.data.oid },
      url: app.globalData.Lottery_url,
      success: function (res) {
        if (res.data.code == '') {
          var giftList = res.data.data;
          that.setData({
            giftList: res.data.data,
            isShowGift: true,
            isShowAward: true
          })
          that.awardList(giftList);
        }else{
          that.setData({
            isShowGift: false
          })
        }
      },
      fail: function (fail) {
        util.showError("网络错误");
      }
    })
  },
  //重构奖品列表
  awardList: function (giftList) {
    var that = this;
    //奖品item设置
    var awardList = [];
    //间距,怎么顺眼怎么设置吧.
    var topAward = 25;
    var leftAward = 25;
    for (var j = 0; j < 8; j++) {
      if (j == 0) {
        topAward = 25;
        leftAward = 25;
      } else if (j < 3) {
        topAward = topAward;
        //166.6666是宽.15是间距.下同
        leftAward = leftAward + 166.6666 + 15;
      } else if (j < 5) {
        leftAward = leftAward;
        //150是高,15是间距,下同
        topAward = topAward + 150 + 15;
      } else if (j < 7) {
        leftAward = leftAward - 166.6666 - 15;
        topAward = topAward;
      } else if (j < 8) {
        leftAward = leftAward;
        topAward = topAward - 150 - 15;
      }
      var list_item = giftList[j];
      awardList.push({ topAward: topAward, leftAward: leftAward, imageAward: list_item.img, name: list_item.name });
    }
    that.setData({
      awardList: awardList
    })
  },

  //开始游戏
  startGame: function () {
    var _this = this;
    if (_this.data.isRunning) return
    _this.setData({ isRunning: true })
    api.POST({
      params: { order_id: _this.data.oid },
      url: app.globalData.Lottery_start_url,
      success: function (res) {
        if (res.data.code == '') {
          var gift = res.data.data;
          for (var i = 0; i < _this.data.giftList.length; ++i) {
            if (_this.data.giftList[i].id == gift.id) {
              var winning_numbers = i;
              break;
            }
          }
          _this.setData({
            winning_numbers: i
          })
          _this.get_win_num(gift);
        } else {
          wx.showModal({
            title: '提示',
            content: (res.data.message != undefined ? res.data.message:'错误'),
            showCancel: false
          })
        }
      },
      fail: function (fail) {
        util.showError("网络错误");
      }
    })
  },
  //获取中奖
  get_win_num: function (gift) {
    var _this = this;
    var indexSelect = 0
    var i = 0;
    var timer = setInterval(function () {
      indexSelect++;
      _this.setData({
        indexSelect: indexSelect % 8
      })
      i++;
      var winning_numbers = _this.data.winning_numbers + 24;
      if (i >= winning_numbers) {
        //去除循环
        clearInterval(timer)
        _this.prize(gift)
      }
    }, (80 - i)) //转盘速度
  },
  //获奖提示
  prize: function (gift) {
    var that = this;
    if (gift.type > 0) {
      if (gift.type == 1) { //集酒卡
        var giftTitle = '抽中一张集酒卡~';
        var gifttext = '已经将集酒卡放置您的“我的优惠券”中啦~';
        var giftButton = '好的';
      } else if (gift.type == 2) { //实物商品
        if (gift.get_type == 1) { //邮寄
          var giftTitle = '抽中一份礼品~';
          var gifttext = '请填写您的收货地址，我们将尽快为您邮寄~';
          var giftButton = '提交';
        } else if (gift.get_type == 2) { //自提
          var giftTitle = '抽中一份礼品~';
          var gifttext = '快把二维码展示给服务员领取礼品吧~';
          var giftButton = '已领取';
        }
      }
      that.setData({
        gift: gift,
        isShowAward: false,
        isShowGift: true,
        isShowButton: true,
        giftTitle: giftTitle,
        gifttext: gifttext,
        giftButton: giftButton
      })

      if (gift.province!=undefined){
        that.setData({
          userName: gift.username,
          telNumber: gift.mobile,
          region: [gift.province, gift.city, gift.town],
          detailInfo: gift.address
        })
      }
    } else {
      wx.showModal({
        title: '提示',
        content: '很遗憾，没有中奖~',
        showCancel: false,
        success: function (res) {
          that.setData({
            isShowGift: false
          })
        }
      })
    }
  },

  //圆点设置
  circleList: function () {
    var _this = this;
    var leftCircle = 7.5;
    var topCircle = 7.5;
    var circleList = [];
    for (var i = 0; i < 24; i++) {
      if (i == 0) {
        topCircle = 15;
        leftCircle = 15;
      } else if (i < 6) {
        topCircle = 7.5;
        leftCircle = leftCircle + 102.5;
      } else if (i == 6) {
        topCircle = 15
        leftCircle = 620;
      } else if (i < 12) {
        topCircle = topCircle + 94;
        leftCircle = 620;
      } else if (i == 12) {
        topCircle = 565;
        leftCircle = 620;
      } else if (i < 18) {
        topCircle = 570;
        leftCircle = leftCircle - 102.5;
      } else if (i == 18) {
        topCircle = 565;
        leftCircle = 15;
      } else if (i < 24) {
        topCircle = topCircle - 94;
        leftCircle = 7.5;
      } else {
        return
      }
      circleList.push({ topCircle: topCircle, leftCircle: leftCircle });
    }
    this.setData({
      circleList: circleList
    })
    //圆点闪烁
    setInterval(function () {
      if (_this.data.colorCircleFirst == '#FFDF2F') {
        _this.setData({
          colorCircleFirst: '#FE4D32',
          colorCircleSecond: '#FFDF2F',
        })
      } else {
        _this.setData({
          colorCircleFirst: '#FFDF2F',
          colorCircleSecond: '#FE4D32',
        })
      }
    }, 1000)
  },


  //选择微信地址
  WXAddress: function () {
    var that = this;
    wx.getSetting({
      success: function (res) {
        if (res.authSetting["scope.address"] != false) {
          that.wxChooseAddress()
        } else {
          wx.showModal({
            title: '警告',
            content: '请授权获取微信地址',
            confirmText: '授权',
            cancelText: '不授权',
            success: function (suress) {
              if (suress.confirm) {
                wx.openSetting({
                  success: function (res) {
                    if (res.authSetting["scope.address"]) {
                      that.wxChooseAddress()
                    }
                  }
                })
              }
            }
          })
        }
      }
    })
  },
  wxChooseAddress: function () {
    var that = this;
    wx.chooseAddress({
      success: function (res) {
        that.setData({
          userName: res.userName,
          region: [res.provinceName, res.cityName, res.countyName],
          detailInfo: res.detailInfo,
          telNumber: res.telNumber
        })
      },
      fail: function (fail) {
        console.log(fail)
        wx.showToast({
          title: '失败',
          image: '../../images/icon_09_2.png',
          duration: 2000
        })
      }
    })
  },


  //选择省市区
  selectAddress: function (e) {
    var value = e.detail.value;
    this.setData({
      region: value
    })
  },
  //检测提示信息
  checkAddressPrompt: function (message) {
    wx.showToast({
      title: message,
      image: '../../images/icon_33.png',
      duration: 1500
    })
  },

  checkAddress: function () {
    var that = this;
    var gift = that.data.gift;
    if (gift.type != 2 || gift.get_type != 1) {  //自提或是集酒卡
      that.setData({
        isShowGift: false
      })
      return;
    }
    if (this.data.userName == '' || this.data.userName == undefined) {
      that.checkAddressPrompt('收货人不能为空');
      return false
    }

    if (!(/^1(3|4|5|7|8)\d{9}$/.test(this.data.telNumber))) {
      that.checkAddressPrompt('手机号不正确');
      return false
    }

    if (this.data.region[1] == '') {
      that.checkAddressPrompt('请选择收货地址');
      return false
    }

    if (this.data.detailInfo == '' || this.data.detailInfo == undefined) {
      that.checkAddressPrompt('请输入详细地址');
      return false
    }

    api.POST({
      params: {
        code: gift.code,
        username: that.data.userName,
        mobile: that.data.telNumber,
        address: that.data.region[0] + that.data.region[1] + that.data.region[2] + that.data.detailInfo
      },
      url: app.globalData.Lottery_submit_url,
      success: function (res) {
        if (res.data.code == '') {
          wx.showToast({
            title: '提交成功',
            icon: 'success',
            duration: 1500
          })
          that.setData({
            isShowGift: false,
          })
        } else {
          that.checkAddressPrompt(res.data.message);
        }
      },
      fail: function (fail) {
        util.showError("网络错误");
      }
    })
  },

  modifyName: function (e) {  //用户名
    this.setData({
      userName: e.detail.value
    })
  },
  modifyPhone: function (e) {  //手机号
    this.setData({
      telNumber: e.detail.value
    })
  },
  modifyAddress: function (e) {  //详细地址
    this.setData({
      detailInfo: e.detail.value
    })
  },
  luckyShow: function () {
    // this.setData({
    //   isShowGift:true
    // })
  }
})